﻿using HybridCLR.Editor;
using HybridCLR.Editor.Commands;
using HybridCLR.Editor.Installer;
using HybridCLR.Editor.Settings;
using NL;
using System;
using System.IO;
using UnityEditor;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace Miya.Hellow.Editor
{
    public class BundleBuilder : /*IPreprocessBuildWithReport,*/IPostprocessBuildWithReport
    {
        class _AssemblyDefinitionData
        {
            public string name;

        }



        // 导出的 热更库 文件主目录
        public static string PATH_BIN_ROOT => Path.Combine(Application.dataPath, "~Bin");
        public static string PATH_AA_BUILD_ROOT => Path.Combine(Application.dataPath, "..\\Library\\com.unity.addressables\\aa\\Android");


        // 导出的 热更清单文件
        static string FILE_NAME_Bill = Path.Combine(Application.dataPath, "~Bin/bill.info");

        // 导出的 热更元数据 主目录
        static string PATH_MetadataRoot => Path.Combine(Application.dataPath, "~Bin/Metadata");

        // 导出的 热更程序集 主目录
        static string PATH_AssemblyRoot => Path.Combine(Application.dataPath, "~Bin/Assembly");

        public int callbackOrder => 99;


        //当开始构建的时候
        //public void  OnPreprocessBuild(BuildReport report)
        //{
        //    Debug.Log($"[Miya.Welcome.Editor.Builder.OnPreprocessBuild]-----START BUILD @{ report.summary.platform} => {report.summary.outputPath}");

        //    BuildHybrid();

        //}
        //当构建完成的时候
        public void OnPostprocessBuild(BuildReport report)
        {
            Debug.Log($"[BundleBuilder.OnPostprocessBuild]-----END BUILD @{report.summary.platform} => {report.summary.outputPath}");

        }
        [MenuItem("MIYA/Build/BuildBundleAll(Hybrid>AA) 构建游戏资源包.=>AA资产输出目录")]
        public static void BuildByShell()
        {

            Builder.ApplyShellBuildParam();


            BuildBundleAll();
        }

        public static void BuildBundleAll(bool hybrid = true, bool aa = true)
        {
            Debug.Log($"[BundleBuilder.BuildBundleAll]:...............................BEGIN");

            bool hybridenable = HybridCLRSettings.Instance.enable;
            if (hybrid && hybridenable)
                BuildHybrid();

            if (aa)
                BuildAddressabe();

            Debug.Log($"[BundleBuilder.BuildBundleAll]:..............Success");
        }



        [MenuItem("MIYA/Build/Hybrid生成~Bin目录的程序集和清单")]
        public static void BuildHybrid()
        {
            Debug.Log($"[HybridBuilder.BuildHybrid]:................BEGIN");
            //11111111111111 如果没安装 ...先安装
            var installer = new InstallerController();
            if (!installer.HasInstalledHybridCLR())
            {
                installer.InstallDefaultHybridCLR();

                Debug.Log($"[HybridBuilder.BuildHybrid]:InstallDefaultHybridCLR..............Success");
            }


            //22222222222222 生成Dll
            try
            {
                // 生成裁剪后的aot dll的时候
                // 会触发 UnityPlayer的构建(BuildPipeline.BuildPlayer)
                // 从而触发 Addressable的构建(AddressableAssetSettings.BuildPlayerContent)
                PrebuildCommand.GenerateAll();

                Debug.Log($"[HybridBuilder.BuildHybrid]:PrebuildCommand.GenerateAll..............Success");
            }
            catch (Exception e)
            {
                Debug.LogError($"[HybridBuilder.BuildHybrid]:Error= {e}  @PrebuildCommand.GenerateAll");
            }


            AssetDatabase.Refresh();

            NLIni bill = new NLIni();
            var settings = HybridCLRSettings.Instance;

            //333333333333333 补充元数据Dll拷贝到资源目录
            var rootpath = SettingsUtil.GetAssembliesPostIl2CppStripDir(EditorUserBuildSettings.activeBuildTarget);


            string _metadatas = "";//记录 元数据文件列表...
            if (settings.patchAOTAssemblies != null)
            {
                foreach (var one in settings.patchAOTAssemblies)
                {

                    if (string.IsNullOrEmpty(one)) continue;

                    var file_from = $"{rootpath}/{one}.dll";
                    var file_to = $"{PATH_MetadataRoot}/{one}.bytes";

                    File.Copy(file_from, file_to, true);

                    _metadatas += $"{one}.bytes;";

                    Debug.Log($"[HybridBuilder.Build]:patchAOTAssemblies {file_from} >>>> {file_to}");
                }
            }
            bill["metadata"] = _metadatas;
            Debug.Log($"[HybridBuilder.BuildHybrid]:metadatas:{_metadatas}..............");


            //444444444444444444444444  热更Dll
            rootpath = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(EditorUserBuildSettings.activeBuildTarget);

            string _hotdlls = "";//记录 热更Dll文件列表...
            if (settings.hotUpdateAssemblies != null)
            {
                foreach (var one in settings.hotUpdateAssemblies)
                {
                    if (string.IsNullOrEmpty(one)) continue;

                    var file_from = $"{rootpath}/{one}.dll";
                    var file_to = $"{PATH_AssemblyRoot}/{one}.bytes";

                    File.Copy(file_from, file_to, true);

                    _hotdlls += $"{one}.bytes;";

                    Debug.Log($"[HybridBuilder.Build]:hotUpdateAssemblies {file_from} >>>> {file_to}");
                }
            }
            bill["hotdll"] = _hotdlls;
            Debug.Log($"[HybridBuilder.BuildHybrid]:_hotdlls:{_hotdlls}..............");

            //444444444444444444444444  程序集 包...
            string _definitions = "";//记录 程序集 包文件列表...
            if (settings.hotUpdateAssemblyDefinitions != null)
            {
                foreach (var one in settings.hotUpdateAssemblyDefinitions)
                {
                    var data = JsonUtility.FromJson<_AssemblyDefinitionData>(one.text);
                    if (data == null || string.IsNullOrEmpty(data.name)) continue;

                    var file_from = $"{rootpath}/{data.name}.dll";
                    var file_to = $"{PATH_AssemblyRoot}/{data.name}.bytes";

                    File.Copy(file_from, file_to, true);

                    _definitions += $"{data.name}.bytes;";

                    Debug.Log($"[HybridBuilder.Build]:hotUpdateAssemblyDefinitions {file_from} >>>> {file_to}");
                }
            }
            bill["assembly"] = _definitions;
            Debug.Log($"[HybridBuilder.BuildHybrid]:_definitions:{_definitions}..............");







            //55555555555555555  记录清单 bill.info

            File.WriteAllText(FILE_NAME_Bill, bill.ToString());

            Debug.Log($"[HybridBuilder.BuildHybrid]:File.WriteAllText({FILE_NAME_Bill})   \n{bill}");

            AssetDatabase.Refresh();

            Debug.Log($"[HybridBuilder.BuildHybrid]:Success..................END");
        }


        [MenuItem("MIYA/Build/AddressabeBundle")]
        public static void BuildAddressabe()
        {
            Debug.Log($"[BundleBuilder.BuildAddressabe]:...............................BEGIN");

            //先清理 
            AddressableAssetSettings.CleanPlayerContent();

            AddressableAssetSettings.BuildPlayerContent();


            //分发资产...
            //AddressabeDistributer.Distribute();

            Debug.Log($"[BundleBuilder.BuildAddressabe]:..............Success");
        }

    }
}

